<?php
require_once 'pages/TMSAdminPublicableItemPage.inc';


/**
 * @property TMSProductImageModel $ProductImageModel
 * @property TMSDiscountModel $DiscountsModel
 * @property TMSNomenclatureDiscountModel $NomenclatureDiscountsModel
 * @property TMSArticleDiscountModel $ArticleDiscountsModel
 * @property TCatalogProductModel $ArticleModel
 */
class TMSAdminProductPage extends TMSAdminPublicableItemPage {	
/**
 * @var TMSProductImageModel
 */
	protected $_ioc_product_image_model_;
	
/**
 * @var TMSDiscountModel
 */	
	protected $_ioc_discounts_model_;

/**
 * @var TMSNomenclatureDiscountModel
 */	
	protected $_ioc_nomenclature_discounts_model_;

/**
 * @var TMSArticleDiscountModel
 */
	protected $_ioc_article_discounts_model_;	
	
/**
 * @var TCatalogProductModel
 */	
	protected $_ioc_article_model_;
	
	private $_discounts_;
	
	public function __get($nm){
		switch ($nm){
			case 'Discounts':{
				if (!$this->_discounts_)
					$this->_discounts_ = $this->DiscountsModel->ProductApplicableDiscounts();
				return $this->_discounts_;
			}break;
			default:return parent::__get($nm);break;
		}
	}	
			
	public function ProductDiscounts(IItem $product){
		$result = array();
		if ($product->Base instanceof TMSNomenclature)
			$temp = $this->NomenclatureDiscountsModel->NomenclatureDiscounts($product);
		if ($product->Base instanceof TMSArticle)
			$temp = $this->ArticleDiscountsModel->ArticleDiscounts($product);
		
		foreach ($temp as $d)
			$result[] = $d->ItemId();
		return $result;		
	}
	
	public function http_ApplyDiscounts(array $dsc, $article = null){
		if (!$article)
			$article = null;
		$exist = $this->ProductDiscounts($article?$this->ArticleModel->GetItem($article):$this->ModelItem);
		$new = array_keys($dsc);
		
		$delete = array_diff($exist, $new);
		$create = array_diff($new,$exist);
		
		if ($article){
			$di = $this->ArticleDiscountsModel->GetDummyItem();
			$di->Article = $article;
		} else {
			$di = $this->NomenclatureDiscountsModel->GetDummyItem();
			$di->Nomenclature = $this->ModelItem->ItemId();
		}
		
		foreach ($delete as $d){
			$di->Discount = $d;
			if ($article)
				$this->ArticleDiscountsModel->Delete($di);
			else
				$this->NomenclatureDiscountsModel->Delete($di);
		}
		
		foreach ($create as $d){
			$di->Discount = $d;
			if ($article)
				$this->ArticleDiscountsModel->Save($di);
			else
				$this->NomenclatureDiscountsModel->Save($di);
		}
	}
	
	public function NomenclatureProperies(){
		return array_filter($this->modelItem->Properties(),create_function('$p','return !in_array($p->Name(),array("ArticleClass","Articles","Images","Quantaty","Reserved"));'));
	}
	
	public function ArticleProperties(IItem $article){
		$filter = '"Added","Nomenclature"';
		if ($this->ModelItem->Articles->ItemCount() == 1)
			$filter .= ',"KitPrice","Price"';
		return array_filter($article->Properties(),create_function('$p','return !in_array($p->Name(),array('.$filter.'));'));
	}

	public function ItemDeleteUrl(IItem $item){
		if ($item->Base instanceof TMSArticle)
			return $this->Url(null,'DeleteArticle',array('artid'=>$item->ItemId()));
		return $this->Url(null,'Delete',array('id'=>$item->ItemId()));
	}	
	
	public function PropertyFieldName(IProperty $p){
		if ($p->Item()->Base instanceof TMSArticle && $p->Item()->ItemId())
			return 'art['.$p->Item()->ItemId().']['.$p->Name().']';
		return parent::PropertyFieldName($p);
	}	
	
	public function DummyArticle(){
		return $this->Model->Products->GetDummyItem(null,$this->ModelItem->ArticleClass);
	}
	
	public function http_CreateArticle(){
		$c = $this->ModelItem->ArticleClass;
		$props = $this->Model->Products->ClassProperties(new $c());
		$data = array();
		foreach ($props as $p){
			$nm = $p->Name();
			if (isset($this->request->$nm)){
				if ($p->Type() == TItemPropertyType::PT_SET)
					$data[$nm] = array_keys($this->request->$nm);
				else
					$data[$nm] = $this->request->$nm;
			}
		}
		if (!$data['Article'])
			unset($data['Article']);
		$data['Nomenclature'] = $this->ModelItem->ItemId();
		
		$this->Model->Products->CreateItem($data,$this->ModelItem->ArticleClass);
	}
	
	public function http_Save(){
		if (is_array($this->request->art)){
			foreach ($this->request->art as $id => $data){
				if (!$data['Article']) unset($data['Article']);
				$this->Model->Products->EditItem($id,$data);
			}			
		}
		parent::http_Save();
	}
	
	public function http_DeleteArticle($artid){
		try {
			$this->Model->Products->DeleteItem($artid);
		} catch (TMySqlException $e){
			if ($e->getCode() == 50004)
				throw new TExposableException('Есть заказы связанные с этим артикулом. Удаление невозможно!');
			else 
				throw $e;
		}
	}
	
	protected function doImagesAdd($data){
		foreach ($data as $file)
			if (!$file->UploadError())	
				$this->ProductImageModel->CreateItem(array('Image'=>$file,'Nomenclature'=>$this->ModelItem));
	}
	
	protected function doImagesDelete($data){
		foreach ($data as $id=>$v)
			if ($v)
			$this->ProductImageModel->DeleteItem($id);
	}
	
	protected function doImagesUpdate($imagesdesc = array(),$imagesorder = array()){
		foreach ($imagesdesc as $id=>$desc)
			$this->ProductImageModel->EditItem($id, array('Description'=>$desc,'OrderNumber'=>isset($imagesorder[$id])?$imagesorder[$id]:null));
	}
	
	public function http_EditImages($addimages = array(),$deleteimages = array(),$imagesdesc = array(),$imagesorder = array()){
		$this->doImagesAdd($addimages);
		$this->doImagesUpdate($imagesdesc,$imagesorder);
		$this->doImagesDelete($deleteimages);
	}	
}